package xin.baizhiedu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import xin.baizhiedu.entity.Employee;
import xin.baizhiedu.service.EmployeeService;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private EmployeeService employeeService;

    @Value("${photo.file.dir}")
    private String realPath;

    /**
     * 删除员工信息
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public String deleteEmployee(Integer id) {

        // 删除头像
        Employee employee = employeeService.findEmployeeById(id);
        File file = new File(realPath, employee.getPhoto());
        if (file.exists()) file.delete();  // 删除头像

        // 删除员工数据
        employeeService.deleteEmployee(id);
        return "redirect:/employee/empList";
    }

    /**
     * 更新员工信息
     *
     * @param employee
     * @param img
     * @return
     */
    @RequestMapping("/update")
    public String updateEmployee(Employee employee, MultipartFile img) throws IOException {
        log.debug("更新之后员工信息：{}", employee);
        // 1.判断是否更新头像
        boolean noEmpty = !img.isEmpty();
        log.debug("是否更新头像：{}", noEmpty);
        if (noEmpty) {
            // 1.删除老的头像 根据id查询原始头像
            String oldPhoto = employeeService.findEmployeeById(employee.getId()).getPhoto();
            File file = new File(realPath, oldPhoto);
            if (file.exists()) file.delete();  // 删除文件
            // 2.处理新的头像上传
            // 原始文件名
            String originalFilename = img.getOriginalFilename();
            // 修改文件名
            String newFileName = uploadPhoto(img, originalFilename);
            // 3.修改员工新的头像名称
            employee.setPhoto(newFileName);
        }

        // 没有更新头像 直接更新基本信息
        employeeService.updateEmployee(employee);

        return "redirect:/employee/empList";
    }

    // 抽取的方法 --- 上传头像方法
    private String uploadPhoto(MultipartFile img, String originalFilename) throws IOException {
        String fileNamePrefix = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-").format(new Date()) + UUID.randomUUID();
        String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = fileNamePrefix + fileNameSuffix;
        img.transferTo(new File(realPath, newFileName));
        return newFileName;
    }

    /**
     * 根据id查询员工详细信息
     * 跳转到更新用户页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/detail")
    public String findEmployeeDetailById(Integer id, Model model) {
        log.debug("当前查询员工id：{}", id);
        // 1.根据id查询员工信息
        Employee employee = employeeService.findEmployeeById(id);
        model.addAttribute("employee", employee);
        log.debug("当前员工信息：{}", employee);
        return "updateEmp"; // 跳转到更新页面
    }


    /**
     * 保存员工信息
     * 文件上传： 1.表单提交方式必须是post  2.表单enctype属性必须为 multipart/form-data
     *
     * @return
     */
    @RequestMapping("/saveEmployee")
    public String saveEmployee(Employee employee, MultipartFile img) throws Exception {
        log.debug("姓名：{}, 薪资：{}, 生日：{}", employee.getName(), employee.getSalary(), employee.getBirthday());
        log.debug("头像文件名：{}", img.getOriginalFilename());
        log.debug("头像文件大小：{}", img.getSize());
        log.debug("上传的路径：{}", realPath);

        // 1.处理头像的上传
        // 原始文件名
        String originalFilename = img.getOriginalFilename();
        // 修改文件名
        String newFileName = uploadPhoto(img, originalFilename);

        // 2.保存员工信息
        employee.setPhoto(newFileName); // 保存头像名字
        employeeService.saveEmployee(employee);
        return "redirect:/employee/empList";  // 保存成功跳转到列表页面
    }

    /**
     * 员工列表
     *
     * @return
     */
    @RequestMapping("/empList")
    // HttpServletRequest request , request 和 model 都是属于请求域
    public String empList(Model model) {
        log.debug("查询所有员工信息");
        List<Employee> employees = employeeService.employeeList();
        model.addAttribute("employees", employees);
        return "empList";
    }

}
